import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import 'base_entity.dart';

class ExceptionHandle {

  // token过期
  static const int unauthorized = 401;

  // 成功
  static const int success = 0;

  // 数据解析失败
  static const int parse_error = -1001;

  // 接口返回空数据
  static const int empty_response = -1002;

  // 连接超时
  static const int connect_timeout = -1003;

  // 网络不可用
  static const int no_network = -1004;

  // 未知错误
  static const int unknown_error = -1;

  // 请求被取消
  static const int cancel_error = -1009;

  /// 根据 Dio 异常类型获取对应的错误码和提示信息
  static BaseEntity<T> handleDioException<T>(DioException e) {
    return switch (e) {
      // 请求被取消
      _ when CancelToken.isCancel(e) => BaseEntity<T>(
          cancel_error,
          '请求已取消',
          null,
        ),

      // 连接超时，请检查网络
      _ when e.type == DioExceptionType.connectionTimeout || e.type == DioExceptionType.receiveTimeout || e.type == DioExceptionType.sendTimeout => BaseEntity<T>(
          connect_timeout,
          '连接超时，请检查网络',
          null,
        ),

      // 网络异常，请检查连接
      _ when e.type == DioExceptionType.connectionError => BaseEntity<T>(
          no_network,
          '网络异常，请检查连接',
          null,
        ),

      // HTTP 状态码处理
      _ when e.response != null => switch (e.response!.statusCode!) {
          // 5xx 服务器错误
          >= 500 => BaseEntity<T>(e.response!.statusCode, '服务器出错了，请稍后再试', null),

          // 404 接口不存在
          404 => BaseEntity<T>(e.response!.statusCode, '接口不存在，请检查路径', null),

          // 其他状态码
          final code => BaseEntity<T>(e.response!.statusCode, '请求失败，状态码：$code', null),
        },

      // 兜底未知错误
      _ => BaseEntity<T>(unknown_error, '未知错误，请重试', null),
    };
  }

  /// 处理通用异常
  static BaseEntity<T> handleUnknownException<T>([String? message]) {
    return BaseEntity<T>(
      unknown_error,
      message ?? '未知错误，请重试',
      null,
    );
  }

  /// 处理空响应
  static BaseEntity<T> handleEmptyResponse<T>() {
    return BaseEntity<T>(
      empty_response,
      '接口返回空数据',
      null,
    );
  }

  /// 处理解析异常
  static BaseEntity<T> handleParseError<T>(String? message) {
    return BaseEntity<T>(
      parse_error,
      '数据解析失败，请重试\n${message?? ''}',
      null,
    );
  }

  /// 统一处理异常
  static BaseEntity<T> handleException<T>(dynamic e) {
    // 统一转换为 BaseEntity 错误
    BaseEntity<T> errorEntity;

    if (e is DioException) {
      // Dio 网络异常（连接超时、404、500等）
      errorEntity = ExceptionHandle.handleDioException(e);
    } else if (e is FormatException || e is TypeError) {
      // JSON 解析失败
      errorEntity = ExceptionHandle.handleParseError(e.toString());
    } else if (e is String && e.isEmpty) {
      // 空响应
      errorEntity = ExceptionHandle.handleEmptyResponse();
    } else if (e is Exception) {
      // 自定义网络异常
      errorEntity = BaseEntity<T>(-1, e.toString(), null);
    } else {
      // 兜底未知异常
      errorEntity = ExceptionHandle.handleUnknownException();
    }
    return errorEntity;
  }
}
